<template>
  <div class="my-orders">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <div>
        <el-input
          v-model="orderNum"
          placeholder="请输入订单号"
          style="width: 200px; margin-left:20px ;"
        />
      </div>
      <div style="margin-right: 20px">
        <el-button type="primary" @click="searchOrders" style="margin-left: 10px">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
    </div>

    <!-- 订单列表 -->
    <div v-for="purchase in pageOrderList" :key="purchase.orderNo" class="purchase-card">
      <div class="purchase-header">
        <div class="purchase-no">
          订单号：{{ purchase.orderNum }}
          <el-tag 
            :type="getStatusType(purchase.status)"
            style="margin-left: 10px"
          >
            {{ getStatusText(purchase.status) }}
          </el-tag>
        </div>
        <div class="purchase-time">下单时间：{{ purchase.createTime }}</div>
      </div>

      <div class="purchase-content">
        <div class="goods-list">
          <div class="goods-item">
            <el-image
              :src="purchase.goods.images"
              fit="cover"
              style="width: 80px; height: 80px"
            />
            <div class="goods-info">
              <div class="goods-name">{{ purchase.goods.goodName }}</div>
              <div class="goods-spec">{{ purchase.remark }}</div>
              <div class="goods-price">
                <span>¥{{ purchase.goods.price }}</span>
                <span class="quantity">x{{ purchase.amount }}</span>
              </div>
            </div>
          </div>
        </div>

        <div class="purchase-summary">
          <div class="amount-info">
            <div>共 {{ purchase.amount}} 件商品</div>
            <div class="total-amount">合计：¥{{ purchase.totalAmount }}</div>
          </div>
          <div class="purchase-actions">
            <el-button 
              v-if="purchase.status == 0"
              type="primary" 
              @click="payOrder(purchase)"
            >
              去支付
            </el-button>
            <el-button 
              v-if="purchase.status == 2"
              type="success" 
              @click="confirmReceive(purchase)"
            >
              确认收货
            </el-button>
            <el-button 
              v-if="purchase.status == 3 && purchase.comment === null"
              type="primary" 
              @click="showReviewDialog(purchase)"
            >
              评价
            </el-button>
            <el-button 
              type="info" 
              @click="viewOrderDetail(purchase)"
            >
              查看详情
            </el-button>
          </div>
        </div>
      </div>

      <!-- 物流信息 -->
      <div v-if="purchase.status >= 2" class="logistics-info">
        <i class="el-icon-truck"></i>
        收货地址： {{purchase.logistics}}
      </div>
    </div>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="[5]"
        layout="total, sizes, prev, pager, next"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 评价弹窗 -->
    <el-dialog
      v-model="reviewDialogVisible"
      title="订单评价"
      width="500px"
    >
      <div class="review-form">
        <div class="rating-section">
          <span class="label">综合评分：</span>
          <el-rate
            v-model="reviewForm.rating"
            :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
          />
        </div>
        <div class="comment-section">
          <span class="label">评价内容：</span>
          <el-input
            v-model="reviewForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入您的评价内容"
          />
        </div>
      </div>
      <template #footer>
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitComment">提交评价</el-button>
      </template>
    </el-dialog>

    <!-- 订单详情弹窗 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="订单详情"
      width="800px"
    >
      <div class="purchase-detail" v-if="currentOrder">
        <div class="detail-section">
          <h4>订单信息</h4>
          <div class="detail-item">
            <span>订单号：</span>
            <span>{{ currentOrder.orderNum }}</span>
          </div>
          <div class="detail-item">
            <span>下单时间：</span>
            <span>{{ currentOrder.createTime }}</span>
          </div>
          <div class="detail-item">
            <span>订单状态：</span>
            <span>{{ getStatusText(currentOrder.status) }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>收货信息</h4>
          <div class="detail-item">
            <span>收货人：</span>
            <span>{{ currentOrder.buyer.username }}</span>
          </div>
          <div class="detail-item">
            <span>联系电话：</span>
            <span>{{ currentOrder.buyer.phone }}</span>
          </div>
          <div class="detail-item">
            <span>收货地址：</span>
            <span>{{ currentOrder.logistics }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>进货来源</h4>
          <div class="detail-item">
            <span>商铺名字：</span>
            <span>{{ currentOrder.seller.username }}</span>
          </div>
        </div>

        <div class="detail-section">
          <h4>商品信息</h4>
            <el-table :data="getItemsArray(currentOrder.goods,currentOrder.remark,currentOrder.payment,currentOrder.amount)" border>
              <el-table-column label="商品图片" width="100">
                <template #default="scope">
                  <el-image
                    :src="scope.row.images"
                    style="width: 50px; height: 50px"
                  />
                </template>
              </el-table-column>
              <el-table-column prop="goodName" label="商品名称" />
              <el-table-column prop="remark" label="规格" width="150" />
              <el-table-column prop="price" label="单价" width="100">
                <template #default="scope">
                  ¥{{ scope.row.price }}
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="数量" width="80" />
              <el-table-column label="小计" width="100">
                <template #default="scope">
                  ¥{{ scope.row.price * scope.row.amount }}
                </template>
            </el-table-column>
          </el-table>
          <div class="purchase-total">
            总计：¥{{ currentOrder.payment }}
          </div>
        </div>

        <!-- 评价信息 -->
        <div class="detail-section" v-if="currentOrder.status == 3 && currentOrder.comment !== null">
          <h4>评价信息</h4>
          <div class="review-info">
            <div class="rating">
              <span>评分：</span>
              <el-rate
                v-model="currentOrder.comment.rating"
                disabled
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
              />
            </div>
            <div class="comment">
              <span>评价：</span>
              <p>{{ currentOrder.comment.content }}</p>
            </div>
            <div class="review-time">
              评价时间：{{ currentOrder.comment.createTime }}
            </div>
          </div>
        </div> -->
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPurchaseListAPI,updatePurchaseAPI } from '@/api/store'
import { useTokenStore } from '@/store/token';
import { addCommentApi } from '@/api/user'

// 用户信息
const tokenStore = useTokenStore()
const wholesaler = tokenStore.wholesaler;

// 订单列表

const purchaseList = ref([])
// 获取订单列表
const pageOrderList = ref([]); // 当前页的数据（用于显示）

const getPurchaseList = async () => {
  const res = await getPurchaseListAPI( {
    buyerId: tokenStore.user.userId,
    buyerType: "批发商"
  })
  purchaseList.value = res.data
  //遍历purchaseList，计算并添加totalAmount字段
  purchaseList.value.forEach(item => {
    if (item.goods && item.goods.price && item.amount) {
      item.totalAmount = item.goods.price * item.amount;
    }
  });
  console.log(purchaseList.value);
  total.value = purchaseList.value.length
  pagePages.value = Math.ceil(total.value / pageSize.value); // 计算总页数
  updatePaginatedList();   // 更新分页数据
}

// 评价相关
const reviewDialogVisible = ref(false)
const currentOrder = ref(null)
const reviewForm = reactive({
  userId: '',
  goodId: '',
  rating: 5,
  comment: ''
})

// 详情弹窗
const detailDialogVisible = ref(false)


// 搜索表单
const orderNum = ref('')

// 搜索订单
const searchOrders = () => {
  // 调用接口搜索订单
  console.log(orderNum.value);  
  getPurchaseListAPI({
    buyerId: wholesaler.wholesalerId,
    buyerType: "批发商",
    orderNum: orderNum.value
  }).then(res => {
    purchaseList.value = res.data
    total.value = purchaseList.value.length
    pagePages.value = Math.ceil(total.value / pageSize.value); // 计算总页数
    updatePaginatedList();   // 更新分页数据
  })
}

const resetSearch = () => {
  orderNum.value = ''
  getPurchaseList()
}

// 查看订单详情
const viewOrderDetail = (purchase) => {
  currentOrder.value = purchase
  // console.log(currentOrder.value)
  detailDialogVisible.value = true
}

// 确认收货
const confirmReceive = (purchase) => {
  ElMessageBox.confirm('确认已收到商品？', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const data = {
      purchaseId: purchase.purchaseId,
      status: 3
    }
    //调用确认收货接口
    updatePurchaseAPI(data).then(() => {
      ElMessage.success('确认收货成功');
      getPurchaseList();  // 刷新订单列表
    }).catch(() => {
      ElMessage.error('更新订单状态失败');
    });
  })
}

// 评价相关方法
const showReviewDialog = (purchase) => {
  currentOrder.value = purchase
  reviewForm.userId = currentOrder.value.buyerId
  reviewForm.goodId = currentOrder.value.goods.goodId
  reviewForm.rating = 5
  reviewForm.content = ''
  console.log(reviewForm)
  reviewDialogVisible.value = true
}

const submitComment = () => {
  if (!reviewForm.content.trim()) {
    ElMessage.warning('请输入评价内容')
    return
  }
  // 提交评价
  addCommentApi(reviewForm).then(res => {
    if (res.code === 0) {
      ElMessage.success('评价成功');
      getPurchaseList();
    } else {
      ElMessage.success('评价提交成功')
    }
  })
  reviewDialogVisible.value = false
}

// 获取商品数组
function getItemsArray(goods, remark, payment, amount) {
  const items = [goods]
  return items.map(item => ({
    ...item,        // 解构商品对象，保留原有字段
    remark,         // 将 remark 添加到每个商品对象
    payment,        // 将 payment 添加到每个商品对象
    amount          // 将 amount 添加到每个商品对象
  }));
}

//分页
const total = ref(0); // 总条数
const pagePages = ref(1); // 总页数
const currentPage = ref(1); // 当前页码
const pageSize = ref(5);  // 每页显示条数

// 更新分页数据（根据 currentPage 和 pageSize）
const updatePaginatedList = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  pageOrderList.value = purchaseList.value.slice(start, end);  // 切割出当前页的数据
};

// 处理每页条数变化
const handleSizeChange = (newSize) => {
  pageSize.value = newSize; // 更新每页显示的条目数
  updatePaginatedList();  // 更新分页数据
};

// 处理当前页码变化
const handleCurrentChange = (newPage) => {
  currentPage.value = newPage; // 更新当前页码
  updatePaginatedList();  // 更新分页数据
};

// 订单状态处理
const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',   // 待付款
    1: 'primary',   // 待发货
    2: 'success',   // 已发货
    3: 'info',      // 已完成
    4: 'danger'     // 已取消
  }
  return statusMap[status]
}

const getStatusText = (status) => {
  const statusMap = {
    0: '待付款',
    1: '待发货',
    2: '已发货',
    3: '已完成',
    4: '已取消'
  }
  return statusMap[status]
}

onMounted(() => {
  getPurchaseList()
})
</script>

<style scoped>
.my-orders {
  padding: 20px;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  height: 80px;
  background-color: #fff;
}

.purchase-card {
  margin-bottom: 20px;
  background: #fff;
  padding: 10px;
}

.purchase-header {
  display: flex;
  justify-content: space-between;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.purchase-content {
  padding: 15px 0;
}

.goods-item {
  display: flex;
  padding: 10px 0;
  border-bottom: 1px solid #f5f5f5;
}

.goods-info {
  margin-left: 15px;
  flex: 1;
}

.goods-name {
  font-size: 14px;
  margin-bottom: 5px;
}

.goods-spec {
  color: #999;
  font-size: 12px;
  margin-bottom: 5px;
}

.goods-price {
  color: #ff4400;
  font-size: 14px;
}

.quantity {
  color: #999;
  margin-left: 10px;
}

.purchase-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
}

.amount-info {
  text-align: right;
}

.total-amount {
  color: #ff4400;
  font-size: 16px;
  font-weight: bold;
  margin-top: 5px;
}

.purchase-actions {
  margin-left: 20px;
}

.logistics-info {
  padding-top: 15px;
  border-top: 1px solid #eee;
  color: #666;
  font-size: 13px;
}

.review-form {
  padding: 20px;
}

.rating-section,
.comment-section {
  margin-bottom: 20px;
}

.label {
  display: inline-block;
  width: 80px;
  color: #666;
}

.review-info {
  padding: 15px;
  background: #f8f8f8;
  border-radius: 4px;
}

.review-info .rating,
.review-info .comment {
  margin-bottom: 10px;
}

.review-info .review-time {
  color: #999;
  font-size: 12px;
}

.pagination {
  margin-top: 20px;
  margin-left: 20%;
  display: flex;
  justify-content: flex-end;
}
</style>